package com.yao.sys.service.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.dto.RoleDto;
import com.yao.sys.entity.dto.UserRoleRelDto;
import com.yao.sys.mapper.UserRoleRelMapper;
import com.yao.sys.mapper.sql.UserRoleRelWrapper;
import com.yao.sys.service.RoleService;
import com.yao.sys.service.UserRoleRelService;
import com.yao.sys.service.UserService;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户角色关系表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Service
@Slf4j
public class UserRoleRelServiceImpl extends ServiceImpl<UserRoleRelMapper, UserRoleRelDto>
    implements UserRoleRelService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void add(UserRoleRelDto dto) {

        this.check(dto);

        // 新增用户-角色关系
        dto.getRoleIdList().stream().map(roleId -> {
            UserRoleRelDto addDto = new UserRoleRelDto();
            BeanUtils.copyProperties(dto, addDto);
            addDto.setRoleId(roleId);
            return addDto;
        }).filter(e -> {
            Wrapper<UserRoleRelDto> query = UserRoleRelWrapper.byUserRole(e.getUserId(), e.getRoleId());
            return Objects.isNull(this.getOne(query));
        }).forEach(this::save);

    }

    @Override
    public void modifyByUserId(UserRoleRelDto dto) {

        // 删除原关系， 重新建立关系
        this.removeByUserId(dto.getUserId());

        this.add(dto);

    }

    @Override
    public void removeByUserId(Integer userId) {
        // 校验用户
        userService.checkUser(userId);

        Wrapper<UserRoleRelDto> update = UserRoleRelWrapper.byUserId(userId);

        // 删除用户-角色关系
        this.remove(update);
    }

    private void check(UserRoleRelDto dto){
        // 校验用户
        userService.checkUser(dto.getUserId());

        // 校验角色
        List<RoleDto> roles = roleService.listByIds(dto.getRoleIdList());
        if (CollUtil.isEmpty(roles) || dto.getRoleIdList().size() != roles.size()) {
            throw new BusinessException("角色列表[{}]有不存在的角色",dto.getRoleIdList());
        }

    }

    @Override
    public List<UserRoleRelDto> listByUserId(Integer userId) {
        return this.list(UserRoleRelWrapper.byUserId(userId));
    }
}